<?php

//////// config ///////
// TODO generalise

    $base = "\/person";
    $fwds = array(
        "rdf"  => array(
            "dir"         => "../alignment/tool/export/linkeddata/output/",
            "contenttype" => "application/rdf+xml",
        ),
        "html" => array(
            "dir"         => "../alignment/tool/export/linkeddata/output/",
            "contenttype" => "text/html",
        ),
    );

/////////

    function serveFile($id, $method){
        global $fwds;
        $file = $fwds[$method]['dir'] . $id . "." . $method;
        if (file_exists($file)){
            header("Content-type: " . $fwds[$method]['contenttype']);
            print file_get_contents($file);
            exit;
        }
    }

    $uri = $_SERVER['REQUEST_URI'];
    if (preg_match("/^$base\/(.*)\.(" . join("|",array_keys($fwds)) .")$/", $uri, $matches)){
        $id = $matches[1];
        $id = str_replace(array('.','/','\\'), "", $id); // strip out periods and slashes to sanitise uri
        $method = $matches[2];

        if (array_key_exists($method, $fwds)){
            serveFile($id, $method);
        }
    } else if (preg_match("/^$base\/(.*)$/", $uri, $matches)){
        $id = $matches[1];

        $offers = array();
        foreach (array_values($fwds) as $fwd){
            $offers[] = $fwd['contenttype'];
        }

        require_once("conneg_class.php");
        $chosen = ConNeg::negotiate(implode(',', $offers));

        foreach (array_keys($fwds) as $fwd_name){
            $fwd = $fwds[$fwd_name];
            if ($chosen == $fwd['contenttype']){
                $file = $fwd['dir'] . $id . "." . $fwd_name;
                if (file_exists($file)){
                    $goto = "$id.$fwd_name";
                    header("HTTP/1.1 303 See Other");
                    header("Location: $goto");
                    header("Content-Type: text/html; charset=utf8");
                    print <<<EOF
<html>
<head><title>Non-Information Resource</title></head>
<body>
<h1>Non-Information Resource</h1>
You should be redirected to <a href="$goto">$goto</a>.
</body>
</html>
EOF;
                    exit;
                }
                break;
            }
        }

        exit;
    }
    print "nothing";
?>
